<?php


namespace App\Http\Admin\Controllers\V1\AdminSystem;


use App\Http\Admin\Controllers\V1\BasisController;
use App\Libs\Common\Cache\ConfigCacheClass;
use Illuminate\Support\Facades\DB;

class ConfigController extends BasisController
{


    public function index(){
        $config = ConfigCacheClass::cacheConfigTypeArr(1);
        return $this->view(compact('config'),'admin_system/config/index');
    }

    /**
     * Todo:: 保存数据
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function save(){
        try{
            $requestData = request();
            $config = $requestData['config'];

            $status = true;
            $message = "";

            // 上传图片
            foreach (request()->all() as $key=>$val){

                if (preg_match("/^_img_.*$/", $key)) {
                    $imgName = str_replace("_img_","",$key);
                    if(isset($config[$imgName])){
                        $rowConfig = $config[$imgName];
                        $name = isset($rowConfig['name'])?$rowConfig['name']:"";
                        $alias = isset($rowConfig['alias'])?$rowConfig['alias']:"";
                        $type_name = isset($rowConfig['type_name'])?$rowConfig['type_name']:"";
                        $explanation = isset($rowConfig['explanation'])?$rowConfig['explanation']:"";
                        $result = $this->saveImg($key,$name,$alias,$type_name,$explanation);
                        if($result['status']){
                           unset($config[$imgName]);
                        }else{
                            $status = false;
                            $message .= "更新图片错误: {$name}({$alias});";
                        }
                    }
                }
            }

            // 变量更新
            foreach ($config as $key=>$val){
                $name = isset($val['name'])?$val['name']:"";
                $alias = isset($val['alias'])?$val['alias']:"";
                $type_name = isset($val['type_name'])?$val['type_name']:"";
                $explanation = isset($val['explanation'])?$val['explanation']:"";
                $value = isset($val['value'])?$val['value']:"";
                if(!empty($name)){
                    $before = DB::table('config')->where('name',$name)->first();
                    $result = true;
                    if($before){
                        $updateData = [];
                        if(!empty($alias) && $before->alias != $alias){
                            $updateData['alias'] = $alias;
                        }
                        if(!empty($type_name) && $before->type_name != $type_name){
                            $updateData['type_name'] = $type_name;
                        }
                        if(!empty($explanation) && $before->explanation != $explanation){
                            $updateData['explanation'] = $explanation;
                        }
                        if(!empty($value) && $before->value != $value){
                            $updateData['value'] = $value;
                        }
                        if($updateData){
                            $result = DB::table('config')->where('name',$name)->update($updateData);
                        }
                    }else{
                        $result = DB::table('config')->insert(array(
                            'name' => $name,
                            'value' => $value,
                            'alias' => $alias,
                            'type_name' => $type_name,
                            'explanation' => $explanation,
                        ));
                    }
                    if(empty($result)){
                        $status = false;
                        $message .= "更新失败: {$name}({$alias});";
                    }
                }
            }
            ConfigCacheClass::removeCacheConfigAll();

            if($status){
                return $this->responseMsg('000000',true,'更新成功',array('url'=>'/admin/v1/system/config/index'));
            }
        }catch (\Exception $e){
            return $this->responseMsg('200000',false,"Error::{$e->getMessage()}",array('url'=>'/admin/v1/system/config/index','wait'=>120));
        }
        return $this->responseMsg('200000',false,"更新失败;{$message}",array('url'=>'/admin/v1/system/config/index','wait'=>120));
    }

    /**
     * Todo:: 配置更新图片
     * @param $hasFile
     * @param $configName
     * @param string $alias
     * @param string $typeName
     * @param string $explanation
     * @return array|\Illuminate\Http\JsonResponse
     */
    protected function saveImg($hasFile,$configName,$alias='',$typeName='',$explanation='')
    {
        // 获取图片信息. 1.检查是否上传文件存在 标题 icon
        if(\request()->hasFile("{$hasFile}")){
            $imgResult = uploadImage("{$hasFile}");
            if($imgResult['status']){
                $address = $imgResult['data']['directory'];
                $before = DB::table('config')->where('name',$configName)->first();
                if($before){
                    $updateData = [
                        'value' => $address,
                    ];
                    if(!empty($alias) && $before->alias != $alias){
                        $updateData['alias'] = $alias;
                    }
                    if(!empty($typeName) && $before->type_name != $typeName){
                        $updateData['type_name'] = $typeName;
                    }
                    if(!empty($explanation) && $before->explanation != $explanation){
                        $updateData['explanation'] = $explanation;
                    }
                    $result = DB::table('config')->where('name',$configName)->update($updateData);
                    if($result && isset($before->value)){
                        deleteImage($before->value);   //删除之前的图片
                    }
                }else{
                    $result = DB::table('config')->insert(array(
                        'name' => $configName,
                        'value' => $address,
                        'alias' => $alias,
                        'type_name' => $typeName,
                        'explanation' => $explanation,
                    ));
                }
                if($result){
                    return responseArray('000000',true,'Success');
                }
            }else{
                return $imgResult;
            }
        }
        return responseArray('200000',false,'上传图片错误');
    }

    /**
     * Todo:: 清理缓存
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function cleanUpViewCache(){
        cleanUpViewCache();
        cleanUpCache();
        return $this->responseMsg('000000',true,'清理成功');
    }

}
